#!/bin/bash

BLOG_PORT=8082
BLOG_MAIN="app.blog_service.main:app"

ADMIN_PORT=8080
ADMIN_MAIN="app.admin_service.main:app"

VENV_PATH="./venv/bin/activate"

# 使用方法: ./service.sh [start|stop] [blog|admin]

# 加载虚拟环境
load_venv() {
    if [ -n "$VENV_PATH" ] && [ -f "$VENV_PATH" ]; then
        source "$VENV_PATH"
        echo "已激活虚拟环境: $VENV_PATH"
    fi
}

case $2 in
    blog)
        PORT=$BLOG_PORT
        MAIN=$BLOG_MAIN
        ;;
    admin)
        PORT=$ADMIN_PORT
        MAIN=$ADMIN_MAIN
        ;;
    *)
        echo "未知服务: $2"
        exit 1
        ;;
esac

case $1 in
    start)
        if lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null ; then
            echo "服务已在运行 (端口: $PORT)"
        else
            echo "启动服务 (端口: $PORT)..."
            load_venv  # 加载虚拟环境
            uvicorn $MAIN --host 0.0.0.0 --port $PORT --reload &
            echo "服务已启动 (端口: $PORT)"
        fi
        ;;
    stop)
        if ! lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null ; then
            echo "服务未在运行 (端口: $PORT)"
        else
            echo "停止服务 (端口: $PORT)..."
            pkill -f "uvicorn.*:$PORT"
            echo "服务已停止 (端口: $PORT)"
        fi
        ;;
    *)
        echo "未知命令: $1"
        echo "用法: $0 [start|stop] [blog|admin]"
        exit 1
        ;;
esac